import React, { ChangeEvent, FC, useEffect, useState } from "react";
import { Input } from "antd";
import style from "./SearchList.module.scss";
import { useNavigate, useSearchParams, useLocation } from "react-router-dom";
import { LIST_SEARCH_KEY } from "../constant";

const SearchList: FC = () => {
  // 搜索后，更新页面地址，用来回显搜索框数据的
  const [values, setValues] = useState("");
  const nav = useNavigate();

  // useLocation :获取当前地址路由
  const { pathname, search } = useLocation();
  // 获取URL参数,并通过 componentDidMount 来设置搜索内容的回显

  const [searchParams] = useSearchParams();
  // console.log(searchParams, "14");

  function searchKey(val: string) {
    console.log("key value :", val);
    nav({
      pathname,
      search: `${LIST_SEARCH_KEY}=${val}`,
    });
  }

  function changKey(event: ChangeEvent<HTMLInputElement>) {
    setValues(event.target.value);
  }

  useEffect(() => {
    let newSearch = searchParams.get(LIST_SEARCH_KEY) || "";
    setValues(newSearch);
  }, [searchParams]);

  return (
    <div className={style.container}>
      <Input.Search
        placeholder="请输入关键字"
        value={values}
        allowClear
        onChange={changKey}
        onSearch={searchKey}
        size="large"
        style={{ width: "200px" }}
      />
    </div>
  );
};

export default SearchList;
